#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(){
    pid_t pid = fork();
    if(pid == -1) printf("create child process failed\n");
    else if(pid == 0){//子进程
       int cnt = 5;
       while(cnt){
           printf("I am a child process, pid = %d, ppid = %d\n", getpid(), getppid());
           cnt--;
           sleep(1);
       }
       exit(11);//随便定一个退出码
    }else if(pid > 0){//父进程
        int ChildStatus = 0;
        while(1){
            pid_t ret = waitpid(pid, &ChildStatus, WNOHANG);//非阻塞等待模式
            if(ret > 0){//捕捉到了子进程
                if(WIFEXITED(ChildStatus))//是否正常退出
                {
                    printf("子进程正常退出，退出码：%d\n", WEXITSTATUS(ChildStatus));
                }else{
                    printf("子进程非正常退出\n");
                }
                break;
            }else if(ret < 0){
                printf("等待失败\n");
                break;
            }else{//ret = 0
                printf("子进程在忙~\n");
                sleep(1);
            }
        }
    }



    return 0;
}
